import java.awt.BorderLayout;
import java.awt.FlowLayout;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.LayoutStyle.ComponentPlacement;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;





public class frmProductos extends JDialog {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private final JPanel contentPanel = new JPanel();
	private JTextField txtCodigo;
	private JTextField txtDescripcion;
	
	static final int SALTO_DE_LINEA = 10;
	
	static Statement comando;
	static Connection con;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		try {
			String url = "jdbc:postgresql://localhost/sucursal.001";
			//Acceso al Driver
			Class.forName("org.postgresql.Driver");
			//La conexión con los parámetros necesarios
			con = DriverManager.getConnection( url,"sysSucursal","ocatavio1");
			//Abrimos la conexión y la iniciamos
			comando = con.createStatement();
			
			frmProductos dialog = new frmProductos();
			dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
			dialog.setVisible(true);
			
			System.out.println("ya salio del dialogo");
						
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Create the dialog.
	 */
	public frmProductos() {
		addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosed(WindowEvent arg0) {
				//Cerramos la conexión
				try {
					comando.execute("END");
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				try {
					comando.close();
				} catch (SQLException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				try {
					con.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
		setBounds(100, 100, 450, 300);
		getContentPane().setLayout(new BorderLayout());
		contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
		getContentPane().add(contentPanel, BorderLayout.CENTER);
		
		JLabel lblCodigo = new JLabel("Codigo:");
		
		txtCodigo = new JTextField();
		txtCodigo.addKeyListener(new KeyAdapter() {
			@Override
			public void keyPressed(KeyEvent arg0) {
				if ( arg0.getKeyCode() == SALTO_DE_LINEA )
				{
					int iCodigo = Integer.parseInt(txtCodigo.getText());
					if ( !conslutar(iCodigo) )
					{
						//arg0.setKeyCode(9); // se supone que podia mandar un tabulador
						txtDescripcion.setText("");
						txtDescripcion.requestFocus();
					}
				}
			}
		});
		txtCodigo.setColumns(10);
		
		JLabel lblDescripcion = new JLabel("Descripcion:");
		
		txtDescripcion = new JTextField();
		txtDescripcion.setColumns(10);
		GroupLayout gl_contentPanel = new GroupLayout(contentPanel);
		gl_contentPanel.setHorizontalGroup(
			gl_contentPanel.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_contentPanel.createSequentialGroup()
					.addContainerGap()
					.addGroup(gl_contentPanel.createParallelGroup(Alignment.LEADING)
						.addComponent(lblDescripcion)
						.addComponent(lblCodigo))
					.addPreferredGap(ComponentPlacement.RELATED)
					.addGroup(gl_contentPanel.createParallelGroup(Alignment.LEADING)
						.addComponent(txtCodigo, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
						.addComponent(txtDescripcion, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
					.addContainerGap(213, Short.MAX_VALUE))
		);
		gl_contentPanel.setVerticalGroup(
			gl_contentPanel.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_contentPanel.createSequentialGroup()
					.addContainerGap()
					.addGroup(gl_contentPanel.createParallelGroup(Alignment.BASELINE)
						.addComponent(lblCodigo)
						.addComponent(txtCodigo, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
					.addPreferredGap(ComponentPlacement.RELATED)
					.addGroup(gl_contentPanel.createParallelGroup(Alignment.BASELINE)
						.addComponent(lblDescripcion)
						.addComponent(txtDescripcion, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
					.addContainerGap(170, Short.MAX_VALUE))
		);
		contentPanel.setLayout(gl_contentPanel);
		{
			JPanel buttonPane = new JPanel();
			buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
			getContentPane().add(buttonPane, BorderLayout.SOUTH);
			{
				JButton okButton = new JButton("OK");
				okButton.addMouseListener(new MouseAdapter() {
					@Override
					public void mouseClicked(MouseEvent arg0) {
						int iCodigo = Integer.parseInt(txtCodigo.getText());
						String sDescripcion = txtDescripcion.getText();
						guarda(iCodigo,sDescripcion);
					}
				});
				okButton.setActionCommand("OK");
				buttonPane.add(okButton);
				getRootPane().setDefaultButton(okButton);
			}
			{
				JButton cancelButton = new JButton("Cancel");
				cancelButton.addMouseListener(new MouseAdapter() {
					@Override
					public void mouseClicked(MouseEvent arg0) {
						System.exit(EXIT_ON_CLOSE);
					}
				});
				cancelButton.setActionCommand("Cancel");
				buttonPane.add(cancelButton);
			}
		}
	}
	
	public boolean guarda(int iCodigo, String sDescripcion)
	{
		boolean bResultado = false;
		
		try{

			//Una variable String para almacenar la sentencia SQL
			String query = "insert into productos(codigo,Descripcion) values (" + iCodigo + ",'" + sDescripcion + "'" + " )";
			/*String query = "insert into productos(codigo,Descripcion) values (?,?)";
			gb.setInt(1, cod);
			gb.setString(2, nombre.getText());
			gb.setString(3, webpage.getText());
			gb.setString(4, telefono.getText());
			gb.setString(5, direccion.getText());
			gb.setString(6, ruc.getText());*/

			System.out.println(query);
			
			//Ejecutamos la consulta SQL
			comando.executeUpdate(query);
			
			}
			catch( SQLException e )
			{
				//Por si ocurre un error
				System.out.println(e.getMessage());
				int op = JOptionPane.showOptionDialog (null,e.getMessage(),"Entrada Invalidad",JOptionPane.YES_OPTION,JOptionPane.ERROR_MESSAGE,null,new Object[] {"ACEPTAR"},"ACEPTAR");
				if (op == 0)
				{
					txtCodigo.requestFocus();
				}
			}
					
			
		return bResultado;		
	}
	public boolean conslutar(int iCodigo)
	{
		boolean bResultado = false;
		
		try{
			
			//Una variable String para almacenar la sentencia SQL
			String query = "select codigo, TRIM(descripcion) as descripcion from productos where codigo = " + iCodigo + ";";
			
			ResultSet resultado = comando.executeQuery(query);
			

			//Ejecutamos la consulta SQL
			if (resultado.next()) {
				txtDescripcion.setText(resultado.getString("descripcion"));
				bResultado = true;
			}

			}
			catch( SQLException e )
			{
				//Por si ocurre un error
				System.out.println(e.getMessage());
				int op = JOptionPane.showOptionDialog (null,e.getMessage(),"Entrada Invalidad",JOptionPane.YES_OPTION,JOptionPane.ERROR_MESSAGE,null,new Object[] {"ACEPTAR"},"ACEPTAR");
				if (op == 0)
				{
					txtCodigo.requestFocus();
				}
			}
					
			
		return bResultado;		
	}
	
}
